import Vue from 'vue'
import Vuex from 'vuex'
import store from '@/vuex/store.js'
import router from '@/router/index.js'
import {createXHR} from "@/common/js/base/createXHR.js"
Vue.use(Vuex);
var phoneList = [];
var files = [];
var server = store.state.ip+'/dynamics/publishtext';//服务器地址

//选取图片来源
function showActionSheet(show) {
  var actionbuttons = [{title: "拍照"}, {title: "相册选取"}];
  var actionstyle = {title: "选择照片", cancel: "取消", buttons: actionbuttons};
  plus.nativeUI.actionSheet(actionstyle, function (e) {
    if (e.index == 1) {
      getImg();
      // router.push({path:'/read/publish'})
    } else if (e.index == 2) {
      galleryImg();
      // router.push({path:'/read/publish'})
    }
  })
}

function getImg() {//打开相机
  plus.camera.getCamera().captureImage(function (p) {
    plus.io.resolveLocalFileSystemURL(p, function (entry) {
      store.state.phone.push({
        src: entry.toLocalURL()
      });
      imgBlobs(entry.toLocalURL())
    });
  });

}

function galleryImg() {//获取相册
  plus.gallery.pick(function (p) {
    store.state.phone.push({
      src: p
    });
    imgBlobs(p)
  });
}

//压缩图片
function compressImage(url){
  plus.zip.compressImage({
      src:url,//src: (String 类型 )压缩转换原始图片的路径
      dst:"_doc/upload",//压缩转换目标图片的路径
      quality:50,//quality: (Number 类型 )压缩图片的质量.取值范围为1-100
      overwrite:true//overwrite: (Boolean 类型 )覆盖生成新文件
    },
    function(event) {
      base64(event.target)
    },function(error) {
    });
}
//图片转base64编码格式
function base64(fun,url) {
  plus.io.resolveLocalFileSystemURL(url, function (entry) {
    entry.file(function (file) {
      let fileReader = new plus.io.FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onloadend = function (p) {
        let imgbase64 = p.target.result.toString();
        fun(imgbase64)
      }
    })
  });
};

function getNowFormatDate() {//获取时间
  var date = new Date();
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    + " " + date.getHours() + seperator2 + date.getMinutes()
    + seperator2 + date.getSeconds();
  return currentdate;
}

function upload1(msg) {
  // loca.onPlusReady()
  let p = store.state.locations;
  let province = p.province;
  let city = p.city;
  let district = p.district;
  let street = p.street;
  let streetNum = p.streetNum;
  let lat = p.lat;
  let lng = p.lng;
  files = store.state.phone;


  if (files.length <= 0 && msg == '') {
    plus.nativeUI.toast("内容不能为空！");
    return;
  }
  var task = plus.uploader.createUpload(server,
    {method: "POST"}, function (t, status) { //上传完成
      console.log(t)
      if (status == 200) {
        let txt = JSON.parse(t.responseText);
        console.log(t)
        if (txt.state == '0') {
          router.push({path: '/information'})
        } else {
          plus.nativeUI.toast(txt.message);
        }
      } else {
        plus.nativeUI.alert("上传失败：" + status + t);
      }
    },
  );
  if (store.state.phone != []) {
    for (var i = 0; i < files.length; i++) {
      var f = store.state.phone[i];
      task.addFile(f.src, {key: 'file' + i, mime: 'file'});
    }
  }
  task.setRequestHeader("authorization", localStorage.userid + '_' + store.state.token);
  task.start();
  store.state.phone = [];
  // });
}


function getBase64Image(img) {
  console.log(img)
  var imgs = document.createElement("img");
  imgs.src = img;
  var canvas = document.createElement("canvas"), //创建canvas元素
    width = imgs.width, //确保canvas的尺寸和图片一样
    height = imgs.height;
  canvas.width = width;
  canvas.height = height;
  canvas.getContext("2d").drawImage(imgs, 0, 0, width, height); //将图片绘制到canvas中
  var dataURL = canvas.toDataURL('image/jpeg'); //转换图片为dataURL
  // return dataURL
  return dataURItoBlob(dataURL)
}

function dataURItoBlob(base64Data) {
  var byteString;
  if (base64Data.split(',')[0].indexOf('base64') >= 0)
    byteString = atob(base64Data.split(',')[1]);
  else
    byteString = unescape(base64Data.split(',')[1]);
  var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
  var ia = new Uint8Array(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ia], {type: mimeString});
}

let imgBlob = [];
let wt = null;
// wt = plus.nativeUI.showWaiting();

function imgBlobs(url) {
  base64(base=>{
    imgBlob.push(dataURItoBlob(base));
    console.log(imgBlob)
  },url);

}

function upload(msg) {
  let p = store.state.locations;
  let data = {
    'userID':localStorage.userid,
    'userName':localStorage.username,
    'tags':'12',
    'detail':msg,
    'lat':JSON.stringify(p.lat),
    'lng':JSON.stringify(p.lng),
    'province':p.province,
    'city':p.city,
    'region':p.district,
    'posDetail':p.street+p.streetNum,
    'permission':'1',
    'collectTime':getNowFormatDate()
  };
  if (imgBlob.length <= 0 && msg == '') {
    plus.nativeUI.toast("内容不能为空！");
    return;
  }
  upload1(data,imgBlob)
}

function upload1(datas,blobs) {
  console.log(blobs)
  var formData = new FormData();
  for (var item in datas){
    formData.append(item,datas[item])
  }
  for (var i=0;i<blobs.length;i++){
    console.log(blobs[i])
    formData.append("image/jpeg", blobs[i], i+'.jpg');
  }

  var xhr = createXHR();
  xhr.onreadystatechange = function () {
    if((xhr.status>=200&&xhr.status<300)||xhr.status == 304){
      let data = JSON.parse(xhr.responseText).data;
      console.log(data);
      router.push({path: '/information'});
      imgBlob = [];
      store.state.commit('phone',[])
    }
  };
  xhr.open('POST',server, false);
  xhr.setRequestHeader("authorization", localStorage.userid + "_" + store.state.token);
  xhr.send(formData);
}

export default {
  showActionSheet,//选取来源
  galleryImg,//打开相册
  getImg,//拍照
  upload,
}
